<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/4/4
 * Time: 15:37
 * Mail:87658989@qq.com
 */

namespace app\base\service;

use think\Db;
use app\base\service;
class Yimei
{

    public function send($phone, $msg)
    {
        $msg = $this->keyWord($msg);
        $ret = $this->sendSms($phone, $msg);
        return $ret;
    }

    /**
     * 短信加入队列
     * @param string $mobile
     * @param array $data
     * @param string $templateCode
     */
    public function addToList($mobile='',$data = [],$templateCode = 'SMS_130911261'){
        $arr = [
            'mobile'=>$mobile,
            'data'  =>$data,
            'code'  =>$templateCode
        ];
        service\Redis::getInstance()->push('send_sms_list',serialize($arr));
    }

    /**
     * 模板发送短信
     * @param $mobile
     * @param array $data
     * @param string $templateCode
     * @return mixed
     */
    public function sendByTemplate($mobile,$data=[],$templateCode='JJDX_001'){
        // 获取模板
        $template    = Db::name('sms_template')->where('template_code',$templateCode)->value('template_text');
        if(!$template) return [0,'模板不存在'];
        // 替换模板变量
        foreach ($data as $k=>$v){
            $search   = '${'.$k.'}';
            $template = str_replace($search,$v,$template);
        }
        return $this->send($mobile,$template);
    }

    public function saveSmsLog($phone, $msg, $status)
    {
        $sms_log            = array();
        $sms_log['content'] = $msg;
        $sms_log['phone']   = $phone;
        $sms_log['status']  = $status;
        $sms_log['add_time']= now_time();
        $sms_log['update_time'] = now_time();
    }

    //注意短信内容最后是签名，必须与登记的一致，签名后面不能有任何字符。所以短信底层接口加上，应用层不用。
    function sendSms($mobilePhone, $msg)
    {
        $msg = $msg . '【晋江出行】';
        //改demo的功能是群发短信和发单条短信。（传一个手机号就是发单条，多个手机号既是群发）
        //您把序列号和密码还有手机号，填上，直接运行就可以了
        //如果您的系统是utf-8,请转成GB2312 后，再提交、
        //请参考 'content'=>iconv( "UTF-8", "gb2312//IGNORE" ,'您好测试短信[XXX公司]'),//短信内容
        //header("Content-Type: text/html; charset=UTF-8");
        $flag = 0;
        $params = '';
        //要post的数据
        $argv = array(
            'sn' => 'SDK-GKG-010-00604', ////替换成您自己的序列号
            'pwd' => strtoupper(md5('SDK-GKG-010-00604' . '3^e-e75a-43')), //此处密码需要加密 加密方式为 md5(sn+password) 32位大写
            'mobile' => $mobilePhone,//手机号 多个用英文的逗号隔开 post理论没有长度限制.推荐群发一次小于等于10000个手机号
            'content' => $msg,//iconv( "GB2312", "gb2312//IGNORE" ,'您好测试短信[XXX公司]'),//'您好测试,短信测试[签名]',//短信内容
            'ext' => '',
            'stime' => '',//定时时间 格式为2011-6-29 11:09:21
            'msgfmt' => '',
            'rrid' => ''
        );
        //构造要post的字符串
        //echo $argv['content'];
        foreach ($argv as $key => $value) {
            if ($flag != 0) {
                $params .= "&";
                $flag = 1;
            }
            $params .= $key . "=";
            $params .= urlencode($value);// urlencode($value);
            $flag = 1;
        }
        $length = strlen($params);
        //创建socket连接
        $fp = fsockopen("sdk.entinfo.cn", 8061, $errno, $errstr, 10) or exit($errstr . "--->" . $errno);
        //构造post请求的头
        $header = "POST /webservice.asmx/mdsmssend HTTP/1.1\r\n";
        $header .= "Host:sdk.entinfo.cn\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . $length . "\r\n";
        $header .= "Connection: Close\r\n\r\n";
        //添加post的字符串
        $header .= $params . "\r\n";
        //发送post的数据
        //echo $header;
        //exit;
        fputs($fp, $header);
        $inheader = 1;
        while (!feof($fp)) {
            $line = fgets($fp, 1024); //去除请求包的头只显示页面的返回数据
            if ($inheader && ($line == "\n" || $line == "\r\n")) {
                $inheader = 0;
            }
            if ($inheader == 0) {
                // echo $line;
            }
        }

//        Log::record('短信发送日志记录：'.$line,Log::DEBUG);
        //<string xmlns="http://tempuri.org/">-5</string>
        $line   = str_replace("<string xmlns=\"http://tempuri.org/\">", "", $line);
        $line   = str_replace("</string>", "", $line);
        $result = explode("-", $line);
        // echo $line."-------------";
        if (count($result) > 1) {
//            Log::write("send msg failed:".$msg, Log::DEBUG);
//            Log::record("send msg failed:".$msg, Log::DEBUG);
            //echo 'send failed,return:'.$line;
            return false;
        } else {
//            Log::write("send msg ok:".$msg, Log::DEBUG);
//            Log::record("send msg ok:".$msg, Log::DEBUG);
            return true;
        }
    }

    /**
     * 短信关键词过滤
     * @param $msg
     * @return mixed
     */
    public function keyWord($msg)
    {
        $msg = str_replace("政协", "政.协", $msg);
        $msg = str_replace("人大", "人.大", $msg);
        return $msg;
    }
}
